package com.chengxiaoxiao.ai_demo.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chengxiaoxiao.ai_demo.entity.MessageInfo;
import com.chengxiaoxiao.ai_demo.entity.OriginalMessage;
import com.chengxiaoxiao.ai_demo.mapper.MessageInfoMapper;
import com.chengxiaoxiao.ai_demo.service.MessageInfoService;
import com.chengxiaoxiao.ai_demo.service.OriginalMessageService;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.SystemMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static dev.langchain4j.data.message.ChatMessageDeserializer.messageFromJson;

/**
 * 消息记录实现类
 *
 * @Description:
 * @Author Cheng Xiaoxiao
 * @Date: 2025/3/12 15:56
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class MessageInfoServiceImpl extends ServiceImpl<MessageInfoMapper, MessageInfo> implements MessageInfoService {
    final OriginalMessageService originalMessageService;

    /**
     * 根据会话ID获取消息记录
     *
     * @param conversationId 会话ID
     * @return 消息记录列表
     */
    @Override
    public List<OriginalMessage> listMessageByConversationId(String conversationId) {
        List<OriginalMessage> messageInfos = originalMessageService.listByConversationId(conversationId);
        if (messageInfos == null) {
            return CollUtil.newArrayList();
        }

        List<OriginalMessage> list = new ArrayList<>();
        for (OriginalMessage messageInfo : messageInfos) {
            ChatMessage chatMessage = messageFromJson(messageInfo.getMessage());
            if (chatMessage instanceof SystemMessage) {
                continue;
            }
            list.add(messageInfo);
        }
        return list;
    }
}